import React, { useCallback, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Form, Input, InputNumber, message } from "antd";
import { UserOutlined, LockOutlined, PhoneOutlined } from "@/config/antdIcon";
import { setToken } from "@/config/cookie";
import { setAuthorization } from "@/config/ajax";
import utils from "@/config/utils";
import ajax from "@/services";

export default function LoginForm() {
  const navigate = useNavigate();
  const [isRegister, setIsRegister] = useState(false);

  const [formData, setFormData] = useState({
    account: "",
    password: "",
  });

  const [registerForm, setRegisterForm] = useState({
    account: "",
    password: "",
    password_ok: "",
    phone: "",
  });

  const [loading, setLoading] = useState(false);

  // 表单信息
  const [form] = Form.useForm();

  // 密码校验规则
  const passwordRules = [
    { required: true, message: "请输入密码" },
    {
      required: true,
      validator: (_, value) => {
        // 空值走第一个校验
        if (!value) return Promise.resolve();
        return utils.pwdRegStrategy(value, "3")
          ? Promise.resolve()
          : Promise.reject(new Error("密码必须包含字母加数字且不低于6位"));
      },
    },
    ({ getFieldValue }) => ({
      validator(_, value) {
        if (
          !value ||
          !utils.pwdRegStrategy(value, "3") ||
          getFieldValue("password") === value
        ) {
          return Promise.resolve();
        }
        return Promise.reject(new Error("两次输入的密码不一致"));
      },
    }),
  ];

  // 登录
  const onSubmit = (data) => {
    setLoading(true);
    ajax.login(data).then(
      (res) => {
        setLoading(false);
        setToken(res.jwt_token);
        setAuthorization(res.jwt_token);
        message.success("登录成功");
        navigate("/home");
      },
      (err) => {
        console.log(err);
        setLoading(false);
      }
    );
  };

  //注册
  const onRegister = (data) => {
    setLoading(true);
    ajax.login(data).then(
      (res) => {
        message.success("注册成功");
        setLoading(false);
        setToken(res.jwt_token);
        setAuthorization(res.jwt_token);
        navigate("/home");
      },
      (err) => {
        setLoading(false);
      }
    );
  };

  const renderRegisterForm = useCallback(() => {
    return (
      <Form
        name="register"
        className="login-form"
        form={form}
        initialValues={registerForm}
        onFinish={onRegister}
      >
        <Form.Item
          name="account"
          rules={[{ required: true, message: "请输入账号" }]}
        >
          <Input
            placeholder="请输入账号"
            maxLength="20"
            prefix={<UserOutlined />}
          />
        </Form.Item>
        <Form.Item name="password" rules={passwordRules.slice(0, 2)}>
          <Input.Password
            placeholder="请输入密码"
            type="password"
            maxLength="20"
            prefix={<LockOutlined />}
          />
        </Form.Item>
        <Form.Item name="password_ok" rules={passwordRules}>
          <Input.Password
            placeholder="确认密码"
            type="password"
            maxLength="20"
            prefix={<LockOutlined />}
          />
        </Form.Item>
        <Form.Item
          name="phone"
          rules={[
            { required: true, message: "请输入手机号" },
            {
              required: true,
              validator: (_, value) => {
                if (!value) return Promise.resolve();
                return utils.phoneTest(value)
                  ? Promise.resolve()
                  : Promise.reject(new Error("请输出正确的手机号"));
              },
            },
          ]}
        >
          <InputNumber
            controls={false}
            placeholder="手机号码"
            maxLength="11"
            prefix={<PhoneOutlined />}
          />
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            className="login-form-button"
            loading={loading}
          >
            注册
          </Button>
        </Form.Item>
      </Form>
    );
  }, [registerForm]);

  return !isRegister ? (
    <Form
      name="login"
      className="login-form"
      form={form}
      initialValues={formData}
      onFinish={onSubmit}
      validateTrigger="onBlur"
    >
      <Form.Item
        name="account"
        rules={[{ required: true, message: "请输入账号" }]}
      >
        <Input
          placeholder="请输入账号"
          maxLength="20"
          prefix={<UserOutlined />}
        />
      </Form.Item>
      <Form.Item name="password" rules={passwordRules.slice(0, 1)}>
        <Input.Password
          placeholder="请输入密码"
          type="password"
          maxLength="20"
          prefix={<LockOutlined />}
        />
      </Form.Item>
      <div className="rt-text">忘记密码请联系管理员</div>
      <Form.Item>
        <Button
          type="primary"
          htmlType="submit"
          className="login-form-button"
          loading={loading}
        >
          登录
        </Button>
      </Form.Item>
      {/* <div className="rt-text">
        还没有账户，请先 <a onClick={() => setIsRegister(true)}>注册</a>
      </div> */}
    </Form>
  ) : (
    renderRegisterForm()
  );
}
